﻿using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Windows.Forms;

// 自定义圆角 Label 类，继承自 Label
public class RoundedLabel : Label
{
    private int cornerRadius = 5;

    public int CornerRadius
    {
        get { return cornerRadius; }
        set
        {
            cornerRadius = value;
            this.Invalidate(); // 当圆角半径改变时，重绘控件
        }
    }

    protected override void OnPaint(PaintEventArgs e)
    {
        // 开启抗锯齿功能
        e.Graphics.SmoothingMode = SmoothingMode.AntiAlias;
        e.Graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
        e.Graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;

        // 创建一个圆角矩形路径
        GraphicsPath path = new GraphicsPath();
        int diameter = cornerRadius * 2;
        Rectangle bounds = new Rectangle(0, 0, this.Width, this.Height);

        path.AddArc(bounds.X, bounds.Y, diameter, diameter, 180, 90);
        path.AddArc(bounds.X + bounds.Width - diameter, bounds.Y, diameter, diameter, 270, 90);
        path.AddArc(bounds.X + bounds.Width - diameter, bounds.Y + bounds.Height - diameter, diameter, diameter, 0, 90);
        path.AddArc(bounds.X, bounds.Y + bounds.Height - diameter, diameter, diameter, 90, 90);
        path.CloseFigure();

        // 设置控件的区域为圆角矩形
        this.Region = new Region(path);

        // 绘制背景
        using (SolidBrush brush = new SolidBrush(this.BackColor))
        {
            e.Graphics.FillPath(brush, path);
        }

        // 绘制文本
        TextRenderer.DrawText(e.Graphics, this.Text, this.Font, bounds, this.ForeColor, TextFormatFlags.HorizontalCenter | TextFormatFlags.VerticalCenter);
    }
}